package com.wjjun.base.ui.activity

import android.os.Bundle
import android.view.WindowManager
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentTransaction
import androidx.lifecycle.lifecycleScope
import com.wjjun.base.ui.listener.IPresenter
import kotlinx.coroutines.launch


/**
 * 基础Activity，实现一些基础功能
 * author : wangjunjun
 * date   : 2022/6/1
 * desc   :
 */
abstract class BaseActivity : AppCompatActivity(), IPresenter {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (isSoftInput()) {
            window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN)
        }
        initParams()
        initViews()
        initContent()
        initData()
    }

    abstract fun initViews()

    /**
     * 是否有键盘输入
     */
    open fun isSoftInput(): Boolean {
        return false
    }

    override fun initData() {
        launch(
            {
                fetchData()
            },
            {
                onFetchDataError(it)
            },
            {
                onFetchDataFinally()
            }
        )
    }

    open suspend fun fetchData(){

    }

    open fun onFetchDataError(e: Throwable) {

    }

    open fun onFetchDataFinally() {

    }

    open fun setSupportFragment(contentId: Int, fragment: Fragment) {
        val beginTransaction = supportFragmentManager.beginTransaction()
        beginTransaction.replace(contentId, fragment)
        beginTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
        beginTransaction.addToBackStack(null)
        beginTransaction.commit()
    }

    /**
     * 执行一个可捕获异常的协程
     */
    fun launch(
        run: suspend () -> Unit,
        error: (suspend (Throwable) -> Unit)? = null,
        complete: (suspend () -> Unit)? = null
    ) {
        lifecycleScope.launch {
            try {
                run()
            } catch (e: Exception) {
                e.printStackTrace()
                error?.let { it(e) }
            } finally {
                complete?.let { it() }
            }
        }
    }

}